import { Node, director, sys, game } from 'cc';

// 平台API类型声明
declare const wx: {
    exitMiniProgram?: (options?: { success?: () => void; fail?: () => void }) => void;
} | undefined;

declare const tt: {
    exitMiniProgram?: () => void;
} | undefined;

declare const jsb: {
    reflection?: {
        callStaticMethod?: (className: string, methodName: string, signature: string) => void;
    };
} | undefined;

/**
 * 游戏退出管理器（全局单例）
 * 功能：处理多平台退出逻辑
 */
export class ExitGame {
    private static _inst: ExitGame;
    private _exitNode: Node;

    // 单例访问器
    public static get inst(): ExitGame {
        if (!this._inst) {
            this._inst = new ExitGame();
        }
        return this._inst;
    }

    /**
     * 直接退出游戏
     */
    public exitGame() {
        this._saveGameData(() => this._executeExit());
    }

    /** 私有方法 */
    private _saveGameData(callback: () => void) {
        setTimeout(callback, 100);
    }

    private _executeExit() {
        // 平台判断
        if (sys.isNative) {
            this._exitNative();
        } else {
            this._exitWeb();
        }
    }

    private _exitNative() {
        switch (sys.os) {
            case sys.OS.ANDROID:
                this._exitAndroid();
                break;
            case sys.OS.IOS:
                director.loadScene("MainMenu"); // iOS不允许直接退出
                break;
            case sys.OS.WINDOWS:
            case sys.OS.OSX:
                if (typeof game.end === 'function') {
                    game.end();
                }
                break;
            default:
                console.warn("不支持的平台");
        }
    }

    private _exitWeb() {
        if (sys.platform === sys.Platform.WECHAT_GAME) {
            wx?.exitMiniProgram?.(); // 微信小游戏
        } else if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) {
            tt?.exitMiniProgram?.(); // 字节小游戏
        } else if (typeof window !== 'undefined') {
            try { 
                window.close(); 
            } catch (e) { 
                window.location.href = "about:blank"; 
            }
        }
    }

    private _exitAndroid() {
        if (typeof jsb !== 'undefined' && jsb.reflection?.callStaticMethod) {
            jsb.reflection.callStaticMethod(
                "org/cocos2dx/javascript/AppActivity",
                "exitGame",
                "()V"
            );
        }
    }
}